﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfumeShopManagement.Model;

namespace PerfumeShopManagement.Controller
{
    public class CustomerController : AbstractBaseController
    {
        public override object GetObjectById(object id)
        {
            int customerId = (int)id;
            var result = (from c in _context.Customers
                          where c.CustomerId.Equals(customerId)
                          select c).FirstOrDefault();

            return result;
        }

        public override List<object> GetAllObjects()
        {
            var result = (from c in _context.Customers
                          select c);
            if (result != null)
                return result.ToList<object>();

            return new List<object>();
        }

        public override List<object> GetObjectsByCriteria(object obj)
        {
            throw new NotImplementedException();
        }

        public override bool Save(object obj)
        {
            Customer customer = (Customer)obj;
            if (_context.Customers.Contains(customer)) // Update
            {
                Customer customerRow = _context.Customers.Single(
                    c => c.CustomerId == customer.CustomerId);
                customerRow.CustomerName = customer.CustomerName;
                customerRow.PhoneNumber = customer.PhoneNumber;
                customerRow.Address = customer.Address;
                _context.SubmitChanges();
            }
            else // Insert
            {
                _context.Customers.InsertOnSubmit(customer);
                _context.SubmitChanges();
            }

            return true;
        }

        public override bool Delete(object obj)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteById(object id)
        {
            bool deleted = false;
            int customerId = (int)id;
            var result = (from c in _context.Customers
                          where c.CustomerId.Equals(customerId)
                          select c).FirstOrDefault();
            if (result != null)
            {
                _context.Customers.DeleteOnSubmit((Customer)result);
                _context.SubmitChanges();
                deleted = true;
            }

            return deleted;
        }
    }
}
